import { EcgWave, type DetailResult } from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { Content, Page } from '@alita/flow';
import {
  setPageNavBar,
  useLocation,
  useNavigate,
  useSearchParams,
} from 'alita';
import {
  Button,
  Card,
  DotLoading,
  Form,
  Grid,
  NoticeBar,
  Popup,
  Radio,
  Space,
  Steps,
  Tabs,
  Tag,
  TextArea,
  Toast,
} from 'antd-mobile';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'; // 导入本地化语言
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

import React, { useEffect, useRef, useState } from 'react';

import { DATE_TIME_FORMAT } from '@/constants';
import { type EcgData, type Study } from '@/pages/types/type';
import { decodeWaveFromHexStr } from '@/utils/ecgdata';
import {
  getRequestInit,
  obsPrifix,
  postRequestInit,
  urlPrefix,
} from '@/utils/http';
import { useModel } from 'alita';
import {
  SetOutline,
  AntOutline,
  ClockCircleOutline,
  FillinOutline,
  FilterOutline,
  ScanCodeOutline,
  TravelOutline,
} from 'antd-mobile-icons';
import { Step } from 'antd-mobile/es/components/steps/step';
import * as echarts from 'echarts';
import styles from './index.less';
const numberFormator = new Intl.NumberFormat();

const WriteReportPopup = ({
  study,
  onSuccess,
}: {
  study: Study;
  onSuccess: () => void;
}) => {
  const [ing, setIng] = useState<boolean>(false);
  const [success, setSuccess] = useState<string>();
  const [fail, setFail] = useState<string>();
  const [visible, setVisible] = useState<boolean>(false);
  type FieldModal = { testResultStatus: string };
  const [form] = Form.useForm<FieldModal>();
  const testResultStatus = Form.useWatch<string>('testResultStatus', form);

  async function onFinish(values: FieldModal) {
    setIng(true);
    setFail(undefined);
    setSuccess(undefined);
    let response: Promise<Response> = fetch(
      `${urlPrefix}/api/study-handle/make-diagnosis`,
      postRequestInit({ ...values, study, ecgParams: study.ecgParams }),
    );
    response
      .then((rsp: Response) => {
        console.log(rsp);
        if (rsp.ok) {
          rsp
            .json()
            .then(async (x: DetailResult<number>) => {
              console.log(x);
              const { data, code, msg } = x;
              console.log('id =', data);
              if (code === 0) {
                onSuccess();
                setSuccess(msg);
                setVisible(false);
                Toast.show({
                  icon: 'success',
                  content: msg,
                });
              } else {
                Toast.show({
                  icon: 'fail',
                  content: msg,
                });
                setFail(msg);
              }
            })
            .catch((reason) => {
              setFail(reason);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}`);
      })
      .finally(() => {
        setIng(false);
      });
  }
  return (
    <React.Fragment>
      <Button
        shape={'rounded'}
        color="primary"
        size="mini"
        onClick={() => setVisible(true)}
      >
        写报告
      </Button>
      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
        destroyOnClose
      >
        <Form
          form={form}
          layout={'vertical'}
          onFinish={onFinish}
          footer={
            <>
              {fail !== undefined && (
                <NoticeBar
                  extra={
                    <Space style={{ '--gap': '12px' }}>
                      {' '}
                      <span onClick={() => setFail(undefined)}>
                        再试一次
                      </span>{' '}
                    </Space>
                  }
                  content={fail}
                  color="alert"
                />
              )}
              <Button
                block
                type="submit"
                disabled={ing || fail !== undefined || success !== undefined}
                loading={ing}
                color="primary"
                size="large"
              >
                {success !== undefined
                  ? '已提交'
                  : fail !== undefined
                    ? '提交失败'
                    : '提交'}
              </Button>
            </>
          }
        >
          <Form.Item
            name="testResultStatus"
            label="诊断结果"
            initialValue={study.preliminaryDiagnosis.testResultStatus}
          >
            <Radio.Group>
              <Space direction="horizontal">
                <Radio value="normal">
                  <Tag color={'success'}>正常</Tag>
                </Radio>
                <Radio value="abnormal">
                  <Tag color={'warning'}>异常</Tag>
                </Radio>
                <Radio value="danger">
                  <Tag color={'danger'}>危急</Tag>
                </Radio>
              </Space>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="criticalLevel"
            required={testResultStatus === 'danger'}
            initialValue={study.preliminaryDiagnosis.criticalLevel}
            disabled={testResultStatus !== 'danger'}
            label="危急等级"
          >
            <Radio.Group>
              <Space direction="horizontal">
                <Radio value="none">
                  <Tag color={'success'}>无</Tag>
                </Radio>
                <Radio value="low">
                  <Tag color={'warning'}>低危</Tag>
                </Radio>
                <Radio value="medium">
                  <Tag color={'#ff6430'}>中危</Tag>
                </Radio>
                <Radio value="high">
                  <Tag color={'danger'}>高危</Tag>
                </Radio>
              </Space>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="impression"
            label={'诊断说明'}
            initialValue={study.preliminaryDiagnosis.impression}
            rules={[{ required: true, message: '诊断说明' }]}
          >
            <TextArea
              placeholder="诊断说明"
              autoSize={{ minRows: 2, maxRows: 3 }}
              showCount
              maxLength={220}
            />
          </Form.Item>

          <Form.Item
            name="criticalDescription"
            label={'危急值'}
            disabled={testResultStatus !== 'danger'}
            initialValue={study.preliminaryDiagnosis.criticalDescription}
            rules={[{ required: true, message: '危急值' }]}
          >
            <TextArea
              placeholder="危急值"
              autoSize={{ minRows: 2, maxRows: 3 }}
              showCount
              maxLength={220}
            />
          </Form.Item>
        </Form>
      </Popup>
    </React.Fragment>
  );
};



declare type ZoomLevel = {
  index: number;
  step: number;
  text: string;
  speeds: number[];
  gains: number[];
};

declare type SpeedItem = {
  index: number;
  image: string;
  text: string;
};
declare type ModeItem = {
  index: number;
  image: string;
  text: string;
  pageSize: number;
};

const BackgroundGrid = ({
  wave,
  ecgData,
}: {
  wave: EcgWave;
  ecgData: EcgData;
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const rulerRef = useRef<HTMLCanvasElement>(null);

  const [zoomLevel, setZoomLevel] = useState<number>(1);
  const [speedIndex, setSpeedIndex] = useState<number>(1);
  const [gainIndex, setGainIndex] = useState<number>(1);
  const [mode, setMode] = useState<number>(0);
  // 当前页，用于绘图
  const [pageIndex, setPageIndex] = useState<number>(0);
  // 控制面板展开/收缩状态
  const [panelExpanded, setPanelExpanded] = useState<boolean>(false);

  const speedItems: SpeedItem[] = [
    {
      index: 0,
      text: '12.5mm/s',
      image: '/static/wave_speed_125.png',
    },
    {
      index: 1,
      text: '25mm/s',
      image: '/static/wave_speed_25.png',
    },
    {
      index: 2,
      text: '50mm/s',
      image: '/static/wave_speed_50.png',
    },
  ];

  const zoomLevels: ZoomLevel[] = [
    {
      index: 0,
      step: 2.5,
      text: '50%',
      speeds: [32, 16, 8],
      gains: [16, 8, 4],
    },
    {
      index: 1,
      step: 5,
      text: '100%',
      speeds: [16, 8, 4],
      gains: [8, 4, 2],
    },
    {
      index: 2,
      step: 10,
      text: '200%',
      speeds: [8, 4, 2],
      gains: [4, 2, 1],
    },
  ];

  const modeItems: ModeItem[] = [
    {
      index: 0,
      pageSize: 1,
      text: '1xN',
      image: '/static/wave_mode_1N.png',
    },
    {
      index: 1,
      pageSize: 2,
      text: '2xN',
      image: '/static/wave_mode_2N.png',
    },
    {
      index: 2,
      text: '3xN',
      pageSize: 3,
      image: '/static/wave_mode_3N.png',
    },
  ];

  const stepX = zoomLevels[zoomLevel].speeds[speedIndex];
  const stepY = zoomLevels[zoomLevel].gains[gainIndex];


  type RulerRect = {
    //path: Path2D | null,
    x: number,
    y: number,
    width: number,
    height: number,
    fillColor: string,// 'rgba(74, 144, 226, 0.7)',
    strokeColor: string,// '#1a73e8',
    handleSize: number,
    isDragging: boolean,
    activeHandle: string | null,
    startX: number,
    startY: number,
    origin: { x: number, y: number; width: number, height: number }
  }


  const [rulerReact, setRulerReact] = useState<RulerRect>({
    //path: new Path2D(),
    x: 200,
    y: 150,
    width: 400,
    height: 300,
    fillColor: 'rgba(74, 144, 226, 0.7)',
    strokeColor: '#1a73e8',
    handleSize: 12,
    isDragging: false,
    activeHandle: null,
    startX: 0,
    startY: 0,
    origin: {
      x: 200,
      y: 150,
      width: 400,
      height: 300
    }
  });

  // 检查是否点击了控制点
  const checkHandleHit = (ctx: CanvasRenderingContext2D, x: number, y: number) => {

    const { width, height, x: ruleX, y: ruleY } = rulerReact;
    const h = rulerReact.handleSize * 1.5; // 扩大点击区域
    const midX = ruleX + width / 2;
    const midY = ruleY + height / 2;

    // 检查顶部控制点
    if (x > midX - h && x < midX + h && y > ruleY - h && y < ruleY + h) {
      return 'top';
    }
    // 检查右侧控制点
    if (x > ruleX + width - h && x < ruleX + width + h && y > midY - h && y < midY + h) {
      return 'right';
    }
    // 检查底部控制点
    if (x > midX - h && x < midX + h && y > ruleY + height - h && y < ruleY + height + h) {
      return 'bottom';
    }
    // 检查左侧控制点
    if (x > ruleX - h && x < ruleX + h && y > midY - h && y < midY + h) {
      return 'left';
    }


    // 检查是否点击了矩形内部
    // console.log( typeof path!);
    // console.log('type=', path ===null );
    // if (ctx.isPointInPath(path!, x, y,"nonzero")) {
    //   return 'move';
    // }
    // const path1 = new Path2D();
    // path1.rect(x, y, width, height);
    // if (ctx.isPointInPath(path1, x, y)) {
    //   return 'move';
    // }
    if (x >= ruleX &&
      x <= ruleX + width &&
      y >= ruleY &&
      y <= ruleY + height) {
      return 'move';
    }

    return null;
  }


  useEffect(() => {
    const canvas = rulerRef.current;
    const ctx = canvas?.getContext('2d');
    if (ctx && canvas) {
      const devicePixelRatio = window.devicePixelRatio || 1;
      const displayWidth = window.innerWidth - 20;
      const displayHeight = window.innerHeight;

      // 设置canvas的实际像素尺寸
      canvas.width = displayWidth * devicePixelRatio;
      canvas.height = displayHeight * devicePixelRatio;

      // 设置canvas的显示尺寸
      canvas.style.width = displayWidth + 'px';
      canvas.style.height = displayHeight + 'px';

      // 缩放绘图上下文以匹配设备像素比
      ctx.scale(devicePixelRatio, devicePixelRatio);

      // 优化渲染质量，提高清晰度
      ctx.imageSmoothingEnabled = false;
      ctx.textRendering = 'optimizeSpeed';

    }
  }, []);

  // 统一的开始事件处理函数（兼容鼠标和触摸）
  const handlePointerDown = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>) => {
    // 如果是触摸事件，阻止默认行为
    if ('touches' in e) {
      e.preventDefault();
    }
    
    const canvas = rulerRef.current;
    const ctx = canvas?.getContext('2d');
    if (!(canvas && ctx)) {
      return;
    }

    const rectPos = canvas.getBoundingClientRect();
    let clientX: number, clientY: number;
    
    // 根据事件类型获取坐标
    if ('touches' in e) {
      // 触摸事件
      const touch = e.touches[0];
      clientX = touch.clientX;
      clientY = touch.clientY;
    } else {
      // 鼠标事件
      clientX = e.clientX;
      clientY = e.clientY;
    }
    
    const pointerX = clientX - rectPos.left;
    const pointerY = clientY - rectPos.top;

    const hit: string | null = checkHandleHit(ctx, pointerX, pointerY);
    console.log(`hit=${hit}`);
    if (hit) {
      setRulerReact(pre => ({
        ...pre, isDragging: true,
        activeHandle: hit,
        startX: pointerX,
        startY: pointerY,
        origin: { x: pre.x, y: pre.y, width: pre.width, height: pre.height }
      }))
    }
  } // end handlePointerDown;

  // 鼠标悬停事件处理函数，用于改变鼠标样式
  const handleMouseHover = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const canvas = rulerRef.current;
    const ctx = canvas?.getContext('2d');
    if (!(canvas && ctx)) {
      return;
    }

    const { isDragging } = rulerReact;
    
    // 如果正在拖拽，不改变鼠标样式
    if (isDragging) return;

    const rectPos = canvas.getBoundingClientRect();
    const pointerX = e.clientX - rectPos.left;
    const pointerY = e.clientY - rectPos.top;

    const hit: string | null = checkHandleHit(ctx, pointerX, pointerY);
    
    // 根据悬停的句柄类型设置不同的鼠标样式
    switch (hit) {
      case 'top':
      case 'bottom':
        canvas.style.cursor = 'ns-resize'; // 垂直调整大小
        break;
      case 'left':
      case 'right':
        canvas.style.cursor = 'ew-resize'; // 水平调整大小
        break;
      case 'move':
        canvas.style.cursor = 'move'; // 移动
        break;
      default:
        canvas.style.cursor = 'default'; // 默认鼠标样式
        break;
    }
  };

  // 统一的移动事件处理函数（兼容鼠标和触摸）
  const handlePointerMove = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>) => {
    // 如果是触摸事件，阻止默认行为
    if ('touches' in e) {
      e.preventDefault();
    }
    
    const canvas = rulerRef.current;
    const ctx = canvas?.getContext('2d');
    if (!(canvas && ctx)) {
      return;
    }

    const { isDragging, startX, startY, activeHandle, width, height, x, y, origin } = rulerReact;

    // 如果不是触摸事件且没有拖拽，处理鼠标悬停样式
    if (!('touches' in e) && !isDragging) {
      handleMouseHover(e as React.MouseEvent<HTMLCanvasElement>);
      return;
    }

    if (!isDragging) return;

    const rectPos = canvas.getBoundingClientRect();
    let clientX: number, clientY: number;
    
    // 根据事件类型获取坐标
    if ('touches' in e) {
      // 触摸事件
      const touch = e.touches[0];
      clientX = touch.clientX;
      clientY = touch.clientY;
    } else {
      // 鼠标事件
      clientX = e.clientX;
      clientY = e.clientY;
    }
    
    const pointerX = clientX - rectPos.left;
    const pointerY = clientY - rectPos.top;

    const dx = pointerX - startX;
    const dy = pointerY - startY;

    switch (activeHandle) {
      case 'move':
        setRulerReact(pre => ({ ...pre, x: origin.x + dx, y: origin.y + dy }))
        break;
      case 'top':
        setRulerReact(pre => ({ ...pre, y: origin.y + dy, height: origin.height - dy }));
        break;
      case 'right':
        setRulerReact(pre => ({ ...pre, width: origin.width + dx }));
        break;
      case 'bottom':
        setRulerReact(pre => ({ ...pre, height: origin.height + dy }));
        break;
      case 'left':
        setRulerReact(pre => ({ ...pre, x: origin.x + dx, width: origin.width - dx }));
        break;
    }// end switch
  };// end handlePointerMove

  // 鼠标离开canvas时重置鼠标样式
  const handleMouseLeave = () => {
    const canvas = rulerRef.current;
    if (canvas) {
      canvas.style.cursor = 'default';
    }
  };

  // 统一的结束事件处理函数（兼容鼠标和触摸）
  const handlePointerUp = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>) => {
    // 如果是触摸事件，阻止默认行为
    if ('touches' in e) {
      e.preventDefault();
    }
    
    const canvas = rulerRef.current;
    if (canvas) {
      canvas.style.cursor = 'default'; // 拖拽结束时重置鼠标样式
    }
    
    setRulerReact(pre => ({ ...pre, isDragging: false, activeHandle: null }));
  }   // end handlePointerUp

  function drawResizeHandles(ctx: CanvasRenderingContext2D) {
    const h = rulerReact.handleSize;
    const midX = rulerReact.x + rulerReact.width / 2;
    const midY = rulerReact.y + rulerReact.height / 2;

    // 控制点直接置于矩形边中点
    drawDiamond(ctx, midX, rulerReact.y, h);         // 顶部
    drawDiamond(ctx, rulerReact.x + rulerReact.width, midY, h); // 右侧
    drawDiamond(ctx, midX, rulerReact.y + rulerReact.height, h); // 底部
    drawDiamond(ctx, rulerReact.x, midY, h);           // 左侧
  }

  function drawDiamond(ctx: CanvasRenderingContext2D, x: number, y: number, size: number) {
    ctx.fillStyle = '#88a1e5ff';
    ctx.beginPath();
    ctx.moveTo(x, y - size);
    ctx.lineTo(x + size, y);
    ctx.lineTo(x, y + size);
    ctx.lineTo(x - size, y);
    ctx.closePath();
    ctx.fill();

  }

  //  rulerReact 发生变更
  useEffect(() => {
    const canvas: HTMLCanvasElement | null = rulerRef.current;
    const ctx = canvas?.getContext('2d');
    if (ctx && canvas) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制填充矩形
      ctx.fillStyle = rulerReact.fillColor;
      const path1 = new Path2D();
      const { x, y, width, height } = rulerReact;
      path1.rect(x, y, width, height);


      // 绘制边框
      ctx.strokeStyle = rulerReact.strokeColor;
      ctx.lineWidth = 2;
      ctx.fill(path1);

      var path = new Path2D();
      let i = -1;
      while (true) {
        ++i;
        var t1 = x - i * width;
        if (t1 >= 0) {
          path.moveTo(t1, 0);
          path.lineTo(t1, canvas.height);
        } else {
          break;
        }
      }
      i = 0;
      while (true) {
        ++i;
        var t1 = x + i * width;
        if (t1 >= 0 && t1 <= canvas.width) {
          path.moveTo(t1, 0);
          path.lineTo(t1, canvas.height);
        } else {
          break;
        }
      }
      ctx.stroke(path);

      // 测量结果的文本区域
      // let p000 = new Path2D(`M${x} ${y} h ${width} v -20 h -${width} Z`);
      // ctx.fill(p000);
      ctx.fillStyle='rgba(130, 138, 41, 0.5)'
      let nameB = new Path2D();
      nameB.rect(x, y-50, width, 40);
      ctx.fill(nameB);
  
      // 

      drawResizeHandles(ctx);

    } // ctx && canvas
  }, [rulerReact])



  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas?.getContext('2d');

    if (ctx && canvas) {
      // 获取设备像素比，解决高DPI显示器模糊问题
      const devicePixelRatio = window.devicePixelRatio || 1;
      const displayWidth = window.innerWidth - 20;
      const displayHeight = window.innerHeight;

      // 设置canvas的实际像素尺寸
      canvas.width = displayWidth * devicePixelRatio;
      canvas.height = displayHeight * devicePixelRatio;

      // 设置canvas的显示尺寸
      canvas.style.width = displayWidth + 'px';
      canvas.style.height = displayHeight + 'px';

      // 缩放绘图上下文以匹配设备像素比
      ctx.scale(devicePixelRatio, devicePixelRatio);

      // 优化渲染质量，提高清晰度
      ctx.imageSmoothingEnabled = false;
      ctx.textRendering = 'optimizeSpeed';

      // 清除画布
      ctx.clearRect(0, 0, displayWidth, displayHeight);
      // 根据设备像素比和设备类型调整线宽
      const isMobileScreen =
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
          navigator.userAgent,
        );
      const baseLineWidth = isMobileScreen ? 0.3 : 0.3;
      ctx.lineWidth = baseLineWidth * Math.min(devicePixelRatio, 2);

      // 启用像素对齐，减少模糊
      ctx.translate(0.5, 0.5);
      const piexPerMM = zoomLevels[zoomLevel].step;
      let mm = piexPerMM;

      ctx.strokeStyle = '#ffe1e1';
      const gridCanvasWidth = window.innerWidth;
      const gridCanvasHeight = window.innerHeight;

      for (let i = 0; i < gridCanvasWidth / mm; i++) {
        ctx.moveTo(i * mm, 0);
        ctx.lineTo(i * mm, gridCanvasHeight);
      }

      for (let i = 0; i < gridCanvasHeight / mm; i++) {
        ctx.moveTo(0, i * mm);
        ctx.lineTo(gridCanvasWidth, i * mm);
      }

      ctx.stroke();

      mm = piexPerMM * 5;
      ctx.beginPath();
      ctx.strokeStyle = '#ffc8c8';

      for (let i = 0; i < gridCanvasWidth / mm; i++) {
        ctx.moveTo(i * mm, 0);
        ctx.lineTo(i * mm, gridCanvasHeight);
      }

      for (let i = 0; i < gridCanvasHeight / mm; i++) {
        ctx.moveTo(0, i * mm);
        ctx.lineTo(gridCanvasWidth, i * mm);
      }
      ctx.stroke();
      //ctx.draw();
      ctx.restore();

      // 绘制波型
      const { leadCount } = ecgData;
      // 每一页上拆线数
      const pageLeadCount = Math.ceil(
        ecgData.leadCount / modeItems[mode].pageSize,
      );

      // 设置波形线宽，根据设备像素比和设备类型调整
      const isMobile =
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
          navigator.userAgent,
        );
      const baseWaveLineWidth = isMobile ? 0.5 : 0.7;

      ctx.lineWidth = baseWaveLineWidth * Math.min(devicePixelRatio, 2);
      ctx.strokeStyle = '#0000ff';

      // 确保像素对齐，提高清晰度
      ctx.save();
      //ctx.translate(0.5, 0.5);
      // ctx.beginPath();

      const { innerWidth: waveCanvasWidth, innerHeight: waveCanvasHeight } =
        window;
      //
      //const chInt = waveCanvasHeight / (pageLeadCount + 1);
      // const blockHeight = waveCanvasHeight / (pageLeadCount + 1);
      const blockHeight = waveCanvasHeight / pageLeadCount;
      //let yOffset = 0;
      //let xOffset = 0;
      let y = 0;
      // ctx.save();

      // 待会放到外面，成为state
      const dataOffset = 0;
      // 待会放到外面，成为：state
      const calibration = 10;

      // 产生一个数据组。
      Array.from(
        { length: pageLeadCount /* 3 */ },
        (_, itx) => pageLeadCount * pageIndex + itx /** 0 1 2 */,
      ).forEach((j, ixt) => {
        const yOffset = blockHeight * (ixt + 1);
        // 取出待处理的data
        var values = ecgData.data[ecgData.leadNames[j]].slice(dataOffset);
        // 接下来，水平方向，使用line to,在每个像素点上画出数据，由于数据
        // 肯定是比像素点多的，所以需要使用使用 stepX ，来隔点取样。
        // 当  stepX 越大时，在同一宽度上，绘制的波型越少，给到的观感是：走速快：
        // 当  stepX 越少时，在同一宽度上，组件的波型越多，组到的观感是：走速慢：
        ctx.strokeStyle = '#0000ff';
        ctx.beginPath();
        values
          .filter((_: number, qx: number) => qx % stepX == 0)
          .filter((_: number, qx: number) => qx < waveCanvasWidth)
          .forEach((iix: number, dlx: number) => {
            if (dlx == 0) {
              ctx.moveTo(calibration, yOffset - iix / stepY);
            } else {
              ctx.lineTo(calibration + dlx, yOffset - iix / stepY);
            }
          });
        ctx.stroke();

        // 绘制定标、导联名称开始
        ctx.strokeStyle = '#000000';
        ctx.fillText(ecgData.leadNames[j], 25, yOffset - 12);
        ctx.beginPath();
        ctx.moveTo(0, yOffset);
        ctx.lineTo(5, yOffset);
        ctx.lineTo(5, yOffset - 200 / stepY);
        ctx.lineTo(15, yOffset - 200 / stepY);
        ctx.lineTo(15, yOffset);
        ctx.lineTo(20, yOffset);
        ctx.stroke();
      });
      /* 绘制QRS开始 */
      let offsetX = 0;
      let qrs0 = 0;
      let qrs1 = 0;
      wave.QrsList.forEach((qrs, j) => {
        var qrs0 = qrs.TT;
        var type: number = qrs.Type;
        offsetX = Math.round((qrs0 - dataOffset) / stepX) + calibration;
        if (offsetX > 0 && offsetX < waveCanvasWidth) {
          let color = 'black';
          if (type === 11) {
            color = 'red';
          }
          if (type === 13) {
            color = 'blue';
          }
          ctx.fillStyle = color;
          ctx.beginPath();
          ctx.moveTo(offsetX - 5, 0);
          ctx.lineTo(offsetX + 5, 0);
          ctx.lineTo(offsetX, 10);
          ctx.fill();
          if (j < wave.QrsList.length - 1) {
            qrs1 = wave.QrsList[j + 1].TT;
            let rr: string = `${qrs1 - qrs0}`;
            const metrics = ctx.measureText(rr);
            ctx.fillText(
              rr,
              offsetX + ((qrs1 - qrs0) / stepX - metrics.width) / 2,
              10,
            );
          }
        }
      });
      // 绘制时间，在底部
      ctx.strokeStyle = '#000000';
      ctx.font = '12px serif';

      let totalSec = Math.floor(ecgData.dataLength / 1000);
      let currentSec = Math.floor(dataOffset / 1000);
      for (let i = currentSec; i < totalSec; i++) {
        let mm = Math.floor((i * 1000 - dataOffset) / stepX);
        if (mm > 0 && mm < waveCanvasWidth) {
          ctx.fillText(i + 's', mm - 5, waveCanvasHeight - 15);
          ctx.moveTo(mm + calibration, waveCanvasHeight);
          ctx.lineTo(mm + calibration, waveCanvasHeight - 12);
          ctx.stroke();
        }
      }
      ctx.restore();

    } // end if ctx
  }, [zoomLevel, speedIndex, gainIndex, mode]);

  return (
    <div style={{ position: 'relative' }}>
      <canvas ref={canvasRef} id="canvasContainer" style={{ position: 'absolute', zIndex: 1 }} ></canvas>
      <canvas ref={rulerRef} id="ruler" style={{ zIndex: 2, position: 'absolute' }}
        onMouseDown={handlePointerDown}
        onMouseMove={handlePointerMove}
        onMouseUp={handlePointerUp}
        onMouseLeave={handleMouseLeave}
        onTouchStart={handlePointerDown}
        onTouchMove={handlePointerMove}
        onTouchEnd={handlePointerUp}
      ></canvas>

      <div
        style={{
          opacity: panelExpanded ? 1 : 0.7,
          zIndex: 3,
          position: 'fixed',
          bottom: 20,
          left: 20,
          background: 'rgba(255, 255, 255, 0.95)',
          backdropFilter: 'blur(10px)',
          borderRadius: '12px',
          padding: panelExpanded ? '16px' : '12px',
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
          border: '1px solid rgba(255, 255, 255, 0.2)',
          display: 'flex',
          flexDirection: 'column',
          gap: panelExpanded ? '12px' : '8px',
          minWidth: panelExpanded ? '200px' : 'auto',
          transition: 'all 0.3s ease',
        }}
      >
        {/* 控制面板标题和切换按钮 */}
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            marginBottom: panelExpanded ? '8px' : '0',
          }}
        >
          {panelExpanded && (
            <div
              style={{
                fontSize: '14px',
                fontWeight: '600',
                color: '#333',
                textAlign: 'center',
                flex: 1,
              }}
            >
              控制面板
            </div>
          )}
          <div
            onClick={() => setPanelExpanded(!panelExpanded)}
            style={{
              marginLeft: panelExpanded ? '8px' : '0',
              cursor: 'pointer',
              transition: 'all 0.3s ease',
            }}
          >
            <SetOutline
              style={{
                fontSize: '24px',
                color: '#1890ff',
                transform: panelExpanded ? 'rotate(45deg)' : 'rotate(0deg)',
                transition: 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
              }}
            />
          </div>
        </div>

        {/* 面板内容 - 根据展开状态显示/隐藏 */}
        {panelExpanded && (
          <>
            <div
              style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}
            >
              <div
                style={{
                  fontSize: '12px',
                  fontWeight: '500',
                  color: '#666',
                  marginBottom: '4px',
                  textAlign: 'center',
                }}
              >
                缩放比例
              </div>
              <Space style={{ justifyContent: 'center' }}>
                <Button
                  size="mini"
                  color={zoomLevel === 0 ? 'primary' : 'default'}
                  onClick={() => setZoomLevel(0)}
                  style={{ minWidth: '50px' }}
                >
                  50%
                </Button>
                <Button
                  size="mini"
                  color={zoomLevel === 1 ? 'primary' : 'default'}
                  onClick={() => setZoomLevel(1)}
                  style={{ minWidth: '50px' }}
                >
                  100%
                </Button>
                <Button
                  size="mini"
                  color={zoomLevel === 2 ? 'primary' : 'default'}
                  onClick={() => setZoomLevel(2)}
                  style={{ minWidth: '50px' }}
                >
                  200%
                </Button>
              </Space>
            </div>

            <div
              style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}
            >
              <div
                style={{
                  fontSize: '12px',
                  fontWeight: '500',
                  color: '#666',
                  marginBottom: '4px',
                  textAlign: 'center',
                }}
              >
                播放速度
              </div>
              <Space style={{ justifyContent: 'center' }}>
                <Button
                  size="mini"
                  color={speedIndex === 0 ? 'primary' : 'default'}
                  onClick={() => setSpeedIndex(0)}
                  style={{ minWidth: '50px' }}
                >
                  慢
                </Button>
                <Button
                  size="mini"
                  color={speedIndex === 1 ? 'primary' : 'default'}
                  onClick={() => setSpeedIndex(1)}
                  style={{ minWidth: '50px' }}
                >
                  中
                </Button>
                <Button
                  size="mini"
                  color={speedIndex === 2 ? 'primary' : 'default'}
                  onClick={() => setSpeedIndex(2)}
                  style={{ minWidth: '50px' }}
                >
                  快
                </Button>
              </Space>
            </div>

            <div
              style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}
            >
              <div
                style={{
                  fontSize: '12px',
                  fontWeight: '500',
                  color: '#666',
                  marginBottom: '4px',
                  textAlign: 'center',
                }}
              >
                信号增益
              </div>
              <Space style={{ justifyContent: 'center' }}>
                <Button
                  size="mini"
                  color={gainIndex === 0 ? 'primary' : 'default'}
                  onClick={() => setGainIndex(0)}
                  style={{ minWidth: '50px' }}
                >
                  矮
                </Button>
                <Button
                  size="mini"
                  color={gainIndex === 1 ? 'primary' : 'default'}
                  onClick={() => setGainIndex(1)}
                  style={{ minWidth: '50px' }}
                >
                  中
                </Button>
                <Button
                  size="mini"
                  color={gainIndex === 2 ? 'primary' : 'default'}
                  onClick={() => setGainIndex(2)}
                  style={{ minWidth: '50px' }}
                >
                  高
                </Button>
              </Space>
            </div>

            <div
              style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}
            >
              <div
                style={{
                  fontSize: '12px',
                  fontWeight: '500',
                  color: '#666',
                  marginBottom: '4px',
                  textAlign: 'center',
                }}
              >
                显示模式
              </div>
              <Space style={{ justifyContent: 'center' }}>
                <Button
                  size="mini"
                  color={mode === 0 ? 'primary' : 'default'}
                  onClick={() => setMode(0)}
                  style={{ minWidth: '50px' }}
                >
                  1P
                </Button>
                <Button
                  size="mini"
                  color={mode === 1 ? 'primary' : 'default'}
                  onClick={() => setMode(1)}
                  style={{ minWidth: '50px' }}
                >
                  2P
                </Button>
                <Button
                  size="mini"
                  color={mode === 2 ? 'primary' : 'default'}
                  onClick={() => setMode(2)}
                  style={{ minWidth: '50px' }}
                >
                  3P
                </Button>
              </Space>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams, setSearchParams] = useSearchParams();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(2);

  // 提交时状态控制
  const [ing, setIng] = useState<boolean>();
  const [fail, setFail] = useState<string>();
  const [success, setSuccess] = useState<string>();
  const [study, setStudy] = useState<Study>();
  const [wave, setWave] = useState<EcgWave>();
  const [ecgData, setEcgData] = useState<EcgData>();
  const [activeKey, setActiveKey] = useState<string>('wave');

  type FieldModal = {
    deviceSerialNumber: string;
    updatedAt: string;
    meta: string;
  };

  const [form] = Form.useForm<FieldModal>();

  const model = useModel('useAuthModel');
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `诊断mapx`,
        pageBackground: '#eee',
      },
    });
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {
    let times = 2;
    if (authOK) {
      fetch(
        `${urlPrefix}/api/study-handle/try-strat-diagnosis-when-get-detail/${searchParams.get(
          'id',
        )}`,
        getRequestInit(),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(({ data, code, msg }: DetailResult<Study>) => {
                if (code === 0) {
                  if (data) {
                    setStudy(data!);
                  } // end if data
                  setLoadOK(msg);
                } else {
                  setLoadFails([...loadFails, msg]);
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载部门：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });

      // 获取波型数据。
      fetch(
        'http://183.3.135.80:25005/Analyze/Wave',
        postRequestInit({
          EcgFileUrl:
            'http://baogangecg-obs.billschen.com/study/b6e6f483-5eee-4238-91fe-5382c09f0fb2/C7IFPQ0K355.ECG',
          uid: study?.uid,
        }),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(({ data, code, msg }: DetailResult<EcgWave>) => {
                if (code === 0) {
                  if (data) {
                    setWave(data!);
                    //  Toast.show({ icon:'success',content:msg });
                    const { Wave } = data!;
                    const x: EcgData = decodeWaveFromHexStr(Wave);
                    setEcgData(x);
                    console.dir(x);
                  } // end if data
                  setLoadOK(msg);
                } else {
                  setLoadFails([...loadFails, msg]);
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })

        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载部门：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
    } // end if authOK
  }
  useEffect(load, [authOK]);

  if (tokening) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在授权...</span>
      </div>
    );
  }

  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入,剩余{loadingTimes}个请求...</span>
      </div>
    );
  }

  const {
    name,
    age,
    ageUnit,
    device,
    sex,
    idCardNo,
    doctor,
    clinicalDepartment,
    diagnosisGroup,
    price,
    ecgParams,
    ecgType,
    fileNames,
    id,
    idCardType,
    pathPrefix,
    uid,
    workingMode,
    livings,
    imageAcquisition,
    preliminaryDiagnosis,
    registered,
    diagnosing,
    diagnosed,
    audited,
    lastLiving,
    currentUserDoxxe,
  } = study!;

  const preR = preliminaryDiagnosis!.testResultStatus;

  return (
    <Page>
      <Content>
        {/* <DemoBlock padding={8}>
          <NavBar
            left={
              <Button
                color="primary"
                size="mini"
                shape="rounded"
                onClick={() => navigate('/')}
              >
                首
              </Button>
            }
            // 未定义导航栏右侧内容！
            onBack={() => navigate(-1)}
          >
            检查单-<Tag color={'#1677ff'}>{lastLiving.standard.label}</Tag>
          </NavBar>
        </DemoBlock> */}

        <div
          style={{
            position: 'fixed',
            left: 0,
            top: '0',
            width: '100%',
            zIndex: 1,
            backgroundColor: '#eee',
          }}
        >
          <Tabs activeKey={activeKey} onChange={setActiveKey}>
            <Tabs.Tab title="波型浏览" key="wave"></Tabs.Tab>
            <Tabs.Tab title="报告编辑" key="report"></Tabs.Tab>
          </Tabs>
        </div>

        <div
          style={{
            paddingTop: 44,
          }}
        >
          {activeKey === 'wave' && (
            <BackgroundGrid wave={wave!} ecgData={ecgData!} />
          )}
          {activeKey === 'report' && (
            <div>
              <Card
                title={
                  <div style={{ fontWeight: 'normal' }}>
                    <AntOutline
                      style={{ marginRight: '4px', color: '#1677ff' }}
                    />
                    患者
                  </div>
                }
                // extra={<RightOutline />}
                // onBodyClick={onBodyClick}
                // onHeaderClick={onHeaderClick}
                style={{ borderRadius: '16px', margin: '10px' }}
              >
                <div className={styles.content}>
                  <Grid columns={1} gap={8}>
                    <Grid.Item>
                      <Space>姓名：{name} </Space>
                    </Grid.Item>
                  </Grid>
                  <Grid columns={2} gap={8}>
                    <Grid.Item>
                      <Space>
                        年龄：{age}({ageUnit})
                      </Space>
                    </Grid.Item>
                    <Grid.Item>
                      <Space>性别：{sex}</Space>
                    </Grid.Item>

                    <Grid.Item>
                      <Space>身份证：{idCardNo}</Space>
                    </Grid.Item>
                  </Grid>
                </div>
              </Card>

              <Card
                title={
                  <div style={{ fontWeight: 'normal' }}>
                    <AntOutline
                      style={{ marginRight: '4px', color: '#1677ff' }}
                    />
                    检查
                  </div>
                }
                // extra={<RightOutline />}
                // onBodyClick={onBodyClick}
                // onHeaderClick={onHeaderClick}
                style={{ borderRadius: '16px', margin: '10px' }}
              >
                <div className={styles.content}>
                  <Grid columns={2} gap={8}>
                    <Grid.Item>
                      <Space>科室：{clinicalDepartment.name} </Space>
                    </Grid.Item>
                    <Grid.Item>
                      <Space>医生：{doctor?.name}</Space>
                    </Grid.Item>
                  </Grid>
                  <Grid columns={2} gap={8}>
                    <Grid.Item>
                      <Space>设备：{device.code} </Space>
                    </Grid.Item>

                    <Grid.Item>
                      <Space>模式：{workingMode}</Space>
                    </Grid.Item>
                  </Grid>
                </div>
              </Card>

              <Card
                title={
                  <div style={{ fontWeight: 'normal' }}>
                    {/* <AntOutline style={{ marginRight: '4px', color: 'rgba(22, 119, 255, 1)' }} /> */}
                    图像
                  </div>
                }
                // extra={<RightOutline />}
                // onBodyClick={onBodyClick}
                // onHeaderClick={onHeaderClick}
                style={{ borderRadius: '16px', margin: '10px' }}
              >
                <div className={styles.content}>
                  <EcgMap wave={wave!} />
                </div>
              </Card>
              <Card
                title={
                  <div style={{ fontWeight: 'normal' }}>
                    <AntOutline
                      style={{
                        marginRight: '4px',
                        color: 'rgba(22, 119, 255, 1)',
                      }}
                    />
                    {ecgType}参数
                  </div>
                }
                // extra={<RightOutline />}
                // onBodyClick={onBodyClick}
                // onHeaderClick={onHeaderClick}
                style={{ borderRadius: '16px', margin: '10px' }}
              >
                <div className={styles.content}>
                  <Grid columns={3} gap={8}>
                    {ecgParams.map(({ name, value }, index) => (
                      <Grid.Item key={index}>
                        <Space>
                          {name}:{value}
                        </Space>
                      </Grid.Item>
                    ))}
                  </Grid>
                </div>
              </Card>

              <Card
                title={
                  <div style={{ fontWeight: 'normal' }}>
                    <AntOutline
                      style={{ marginRight: '4px', color: '#1677ff' }}
                    />
                    诊断过程
                  </div>
                }
                // extra={<RightOutline />}
                // onBodyClick={onBodyClick}
                // onHeaderClick={onHeaderClick}
                style={{ borderRadius: '16px', margin: '10px' }}
              >
                <div className={styles.content}>
                  <Steps
                    direction="vertical"
                    current={livings.length - 1}
                    style={{
                      '--title-font-size': '17px',
                      '--description-font-size': '15px',
                      '--indicator-margin-right': '12px',
                      '--icon-size': '22px',
                    }}
                  >
                    <Step
                      title="登记"
                      icon={<FillinOutline />}
                      description={
                        <>
                          <Grid columns={1} gap={8}>
                            <Grid.Item>
                              <Space>患者：{name} </Space>
                            </Grid.Item>
                          </Grid>
                          <Grid columns={1} gap={8}>
                            <Grid.Item>
                              <Space>
                                年龄：{age}({ageUnit}){' '}
                              </Space>
                            </Grid.Item>
                            <Grid.Item>
                              <Space>性别：{sex}</Space>
                            </Grid.Item>

                            <Grid.Item>
                              <Space>身份证：{idCardNo}</Space>
                            </Grid.Item>
                          </Grid>
                        </>
                      }
                    ></Step>
                    <Step
                      title="采集"
                      description={
                        <>
                          <Grid columns={1} gap={4}>
                            <Grid.Item>
                              <Space>
                                时间：
                                {dayjs(imageAcquisition.start).format(
                                  DATE_TIME_FORMAT,
                                )}
                              </Space>
                            </Grid.Item>
                          </Grid>
                          <Grid columns={1} gap={4}>
                            <Grid.Item>
                              <Space>
                                数据：
                                <a
                                  href={`${obsPrifix}/${imageAcquisition.fileNames[0]}`}
                                  target="_blank"
                                >
                                  {' '}
                                  {imageAcquisition.fileNames[0].split('/')[2]}
                                </a>
                              </Space>
                            </Grid.Item>
                          </Grid>
                          <Grid columns={1} gap={4}>
                            <Grid.Item>
                              <Space>
                                医生：{imageAcquisition?.doctor.name}
                              </Space>
                            </Grid.Item>
                          </Grid>
                          <Grid columns={1} gap={4}>
                            <Grid.Item>
                              <Space></Space>
                            </Grid.Item>
                          </Grid>
                          <Grid columns={1} gap={4}>
                            <Grid.Item>
                              <Space></Space>
                            </Grid.Item>
                          </Grid>
                        </>
                      }
                      icon={<ScanCodeOutline />}
                    />
                    <Step
                      title="AI初筛"
                      description={
                        <>
                          <Grid columns={1} gap={4}>
                            <Grid.Item>
                              <Space>
                                诊断结果：
                                <Tag
                                  color={
                                    preR === 'normal'
                                      ? 'success'
                                      : preR === 'abnormal'
                                        ? 'warning'
                                        : 'danger'
                                  }
                                >
                                  {preliminaryDiagnosis!.testResultStatus}
                                </Tag>{' '}
                              </Space>
                            </Grid.Item>
                          </Grid>
                          <Grid columns={1} gap={4}>
                            <Grid.Item>
                              <Space>
                                诊断说明：{preliminaryDiagnosis!.impression}{' '}
                              </Space>
                            </Grid.Item>
                          </Grid>
                          <Grid columns={1} gap={4}>
                            <Grid.Item>
                              <Space>
                                危急等级：{preliminaryDiagnosis!.criticalLevel}{' '}
                              </Space>
                            </Grid.Item>
                          </Grid>
                          <Grid columns={1} gap={4}>
                            <Grid.Item>
                              <Space>
                                危急说明：
                                {preliminaryDiagnosis!.criticalDescription}{' '}
                              </Space>
                            </Grid.Item>
                          </Grid>
                        </>
                      }
                      icon={<FilterOutline />}
                    />
                    <Step
                      title="受理"
                      description={
                        <>
                          <Space wrap>
                            {dayjs(registered.start).format(DATE_TIME_FORMAT)}
                          </Space>
                        </>
                      }
                      icon={<TravelOutline />}
                    />

                    {diagnosing && (
                      <Step
                        title={
                          !diagnosed
                            ? `诊断中(${dayjs(diagnosing.start)
                              .locale('zh-cn')
                              .fromNow()}开始)`
                            : `开始诊断(${dayjs(diagnosing.start)
                              .locale('zh-cn')
                              .fromNow()})`
                        }
                        description={
                          <>
                            <Grid columns={1} gap={4}>
                              <Grid.Item>
                                <Space>
                                  报告医生：{diagnosing.leader!.name}
                                </Space>
                              </Grid.Item>
                            </Grid>

                            <Grid columns={1} gap={4}>
                              <Grid.Item>
                                <Space wrap>
                                  开始时间：
                                  {dayjs(diagnosing.start).format(
                                    DATE_TIME_FORMAT,
                                  )}
                                </Space>
                              </Grid.Item>
                            </Grid>
                            {currentUserDoxxe && (
                              <Grid columns={1} gap={4}>
                                <Grid.Item>
                                  <Space wrap>
                                    <WriteReportPopup
                                      study={study!}
                                      onSuccess={load}
                                    />
                                  </Space>
                                </Grid.Item>
                              </Grid>
                            )}
                          </>
                        }
                        icon={
                          <ClockCircleOutline
                            color={!diagnosed ? '#ee8924c8' : 'success'}
                          />
                        }
                      />
                    )}

                    {diagnosed && (
                      <Step
                        title={`${diagnosed.leader!.name}报告`}
                        description={
                          <>
                            <Grid columns={1} gap={4}>
                              <Grid.Item>
                                <Space>
                                  诊断结果：
                                  <Tag
                                    color={
                                      preR === 'normal'
                                        ? 'success'
                                        : preR === 'abnormal'
                                          ? 'warning'
                                          : 'danger'
                                    }
                                  >
                                    {diagnosed!.testResultStatus}
                                  </Tag>
                                </Space>
                              </Grid.Item>
                            </Grid>
                            <Grid columns={1} gap={4}>
                              <Grid.Item>
                                <Space>诊断说明：{diagnosed!.impression}</Space>
                              </Grid.Item>
                            </Grid>
                            <Grid columns={1} gap={4}>
                              <Grid.Item>
                                <Space>
                                  危急等级：{diagnosed!.criticalLevel}
                                </Space>
                              </Grid.Item>
                            </Grid>
                            <Grid columns={1} gap={4}>
                              <Grid.Item>
                                <Space>
                                  危急说明：{diagnosed!.criticalDescription}
                                </Space>
                              </Grid.Item>
                            </Grid>
                          </>
                        }
                        icon={<FilterOutline />}
                      />
                    )}

                    {/* <Step
                                        title="开始诊断"
                                        description={<>
                                        <Space wrap>{dayjs(registered.start).format( DATE_TIME_FORMAT, )}</Space>
                                        </>}
                                        icon={<CheckCircleFill />}
                                    /> */}
                  </Steps>
                </div>
              </Card>
            </div>
          )}
        </div>
      </Content>
    </Page>
  );
};
